//
//  SignInVC.swift
//  LeGou
//
//  Created by lxm on 2022/8/31.
//

import UIKit

class SignInVC: ZMViewController, UITableViewDelegate, UITableViewDataSource, ListRequestObjct {

    //MARK:--------------------属性--------------------
    var info = ZMUtil.fastNilBehavior(type: SingInfo.self)
        
    // 0 微信 1 支付宝
    var payType = ""
    
    var listData = [Record]()
    var page = 1
    var pageSize = 10
    var refreshScrollView : UIScrollView {
        return tableView
    }
    
    //MARK:--------------------UI控件--------------------
    @IBOutlet weak var topOneContent: UIView!
    
    @IBOutlet weak var topFloat: UIView!
    
    @IBOutlet weak var signButton: UIButton!
    
    @IBOutlet weak var signNum: UILabel!
    
    @IBOutlet weak var hadSign: UILabel!
    
    @IBOutlet weak var today: UILabel!
    
    @IBOutlet weak var month: UILabel!
    
    @IBOutlet weak var all: UILabel!
    
    let loading = XMLoadingView()
    
    @IBOutlet weak var tableView: UITableView!
    
    @IBOutlet weak var signContent: UIView!
    
    @IBOutlet weak var tableH: NSLayoutConstraint!
    
    //MARK:--------------------生命周期--------------------
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        addConstraints()
        bindAction()
        loading.showInView(fatherView: view)
        getTaskInfo()
    }
    
    override func viewWillLayoutSubviews() {
        super.viewWillLayoutSubviews()
        topOneContent.style.GradientLeftToRight(Top: "#F7CDC8".zm.hex(), Bottom: UIColor.zm.color(hexString: "#F7CDC8", 0.49))
        view.style.GradientLeftToRight(Top: UIColor.zm.RGBA(r: 213, g: 96, b: 66, a: 1), Bottom: UIColor.zm.RGBA(r: 177, g: 57, b: 42, a: 1))
        
        ZMUtil.clipCircle(view: topFloat, Corner: [.topLeft, .bottomLeft], radius: 15)
        
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        self.getTaskInfo()
    }
    //MARK:--------------------UI--------------------
    func setUI() {
        title = "签到"
        tableView.delegate = self
        tableView.dataSource = self
        tableView.zm.register(nibName: "SignRecordCell", reuserId: "SignRecordCell")
        
        addRefresh(scrollView: tableView, addHead: false) { [weak self] refresh in
            guard let self = self else {return}
            self.getList()
        }
        
        getList()
    }
    
    func addConstraints() {
        
    }
    
    //MARK:--------------------methods--------------------
    func bindAction() {
        info.subscribe(onNext:{ [unowned self] resp in
            guard let r = resp else {
                signNum.attributedText = "0".zm.append(str: "次", attri: ["f" : "16m"])
                self.hadSign.text = "已签x0"
                return
            }
            self.signNum.attributedText = "\(r.daySignInTimes)".zm.append(str: "次", attri: ["f" : "16m"])
            self.hadSign.text = "已签x\(r.daySignedInTimes)"
            self.today.text = "\(r.dayBidTimes)"
            self.month.text = "\(r.monthBidTimes)"
            self.all.text = "\(r.cumulativeBidTimes)"
            if r.daySignInTimes > 0 {
                self.signButton.style.GradientLeftToRight(left: "#FFD338".zm.hex(), right: "#FFA51F".zm.hex())
                self.signButton.setTitleColor("CD2B1D".zm.hex(), for: .normal)
                self.signButton.isEnabled = true
            } else {
                self.signButton.style.GradientLeftToRight(left: Style.disableColor, right: Style.disableColor)
                self.signButton.setTitleColor(.white, for: .normal)
                self.signButton.isEnabled = false
            }
        }).disposed(by: disposeBag)
        
        tableView.rx.observe(CGSize.self, "contentSize").subscribe(onNext:{ [unowned self] resp in
            if let r = resp {
                self.tableH.constant = r.height
            }
        }).disposed(by: disposeBag)
    }

    @IBAction func onBottomTask(_ sender: Any) {
//        self.navigationController?.popViewController(animated: true)
        CATransaction.setCompletionBlock {
            guard let tab = UIApplication.shared.keyWindow?.rootViewController as? UITabBarController else {return}
            tab.selectedIndex = 0
        }
        CATransaction.begin()
        self.navigationController?.popToRootViewController(animated: true)
        CATransaction.commit()
    }
    
    func getTaskInfo() {
        AuctionAPI.signInfo.rxRequest(type: SingInfo.self).subscribe(onNext:{ [unowned self] resp in
            self.loading.hideView(anmation: true)
            self.info.accept(resp)
        }, onError: { e in
            self.loading.showError(e.localizedDescription)
        }).disposed(by: disposeBag)
    }
    
    func getList() {
        let pa = ["limit" : pageSize, "page" : page]
        ZMUtil.listRequest(type: Record.self, api: AuctionAPI.signRecrodList(pa)) { resp in
            self.listRequest(resp)
        }
    }
    
    
    @IBAction func onSignIn(_ sender: Any) {
        guard let info = info.value, info.daySignInTimes > 0 else {
            ZMToast.showToast(title: "今日可签到次数已用完")
            return
        }
        ZMToast.showActivity()
        ZMADManager.shard.showZMVideoAd(vc: self, slot: "11") {
            ZMToast.hiddenActivity()
        } complete: {
            self.adOver(flag: true)
        } failed: { error in
            ZMToast.showToast(title: "该任务未完成观看，奖励失效！")
            self.adOver(flag: false)
        }
    }
    
    func adOver(flag : Bool) {
        AuctionAPI.signIn(["successType" : flag ? 1 : 0]).rxRequestNullAble(type: Any.self).subscribe(onNext:{ [unowned self] resp in
            self.getTaskInfo()
            self.page = 1
            self.getList()
        }).disposed(by: disposeBag)
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        self.signContent.isHidden = listData.count == 0
        return listData.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SignRecordCell") as! SignRecordCell
        let data = listData[indexPath.row]
        if data.number > 0 {
            cell.title.text = "竞购次数（已发放）"
            cell.num.textColor = Style.mainColor
            cell.num.text = "+\(data.number)"
        } else {
            cell.title.text = "竞购次数（广告未完成奖励失效）"
            cell.num.text = "\(data.number)"
            cell.num.textColor = UIColor.zm.color333333()
        }
        cell.subTitle.text = data.createTime
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        68
    }


}


extension SignInVC {
    struct SingInfo : HandyJSON {
        /// 累计已获竞购（次数）
        var cumulativeBidTimes = 0
        /// 今日已获竞购（次数）
        var dayBidTimes = 0
        /// 今日可签到次数
        var daySignInTimes = 0
        /// 今日已签到次数
        var daySignedInTimes = 0
        /// 本月已获竞购（次数）
        var monthBidTimes = 0
    }
    
    struct Record : HandyJSON {
        /// 创建日期
        var createDay = ""
        /// 创建日期
        var createTime = ""
        /// id
        var id = 0
        /// number
        var number = 0
        /// type
        var type = 0
        /// uid
        var uid = 0
    }
}
